<template>
  <div class="app-container bg-gray">
    <transition name="fade-transform" mode="out-in">
      <router-view />
    </transition>
    <el-card v-if="isShow" class="box-1">
      <div class="header">
        <div class="bar">
          <el-select v-model="searchTerms.source" placeholder="来源" class="select" clearable @change="getData">
            <el-option v-for="item in sourceList" :key="item.id" :label="item.source_name" :value="item.source_name" />
          </el-select>
          <el-select v-model="searchTerms.cust_state" placeholder="状态" class="select" clearable @change="getData">
            <el-option :value="1" label="已激活"/>
            <el-option :value="0" label="未激活"/>
          </el-select>
          <el-select v-model="searchTerms.recommend" placeholder="指派人" class="select" filterable clearable @change="getData">
            <el-option-group
              v-for="group in allMemberList"
              :key="group.label"
              :label="group.label">
              <el-option
                v-for="item in group['personnel']"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-option-group>
          </el-select>
          <el-select v-model="searchTerms.contact_status" placeholder="逾期 | 未联系" class="select" clearable @change="getData">
            <el-option value="逾期" label="逾期"/>
            <el-option value="未联系" label="未联系"/>
          </el-select>
          <el-tooltip content="注册时间" placement="top">
            <el-date-picker
              v-model="searchTerms.date1"
              class="picker"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              @change="getData"/>
          </el-tooltip>
          <el-tooltip content="下次联系时间" placement="top">
            <el-date-picker
              v-model="searchTerms.date2"
              class="picker"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              @change="getData"/>
          </el-tooltip>
          <el-input v-model="searchTerms.searchValue" placeholder="请输入内容" class="search-input" @change="getData" />
          <el-button type="success" class="do-btn" icon="el-icon-search" @click="getData">搜索</el-button>
        </div>
        <div>
          <el-button v-if="queryMatch(107)" :loading="downloadLoading" :disabled="downloadLoading" type="primary" icon="el-icon-printer" @click="handleDownload">批量导出</el-button>
          <el-button v-if="queryMatch(102)" type="danger" icon="el-icon-share" @click="toTransfer(1)">批量指派</el-button>
          <el-button v-if="queryMatch(102)" type="danger" icon="el-icon-delete" @click="toDeleteMore">批量删除</el-button>
          <!--<el-button type="danger" icon="el-icon-share" @click="toTransfer(0)">批量转移</el-button>-->
          <span class="flex-1" />
          <column-controller :check-items="th" @change="columnCheck" />
        </div>
      </div>
      <el-table v-loading="tableLoading" :data="tableData" :max-height="tableMaxHeight" border highlight-current-row @sort-change="handleSortChange" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" header-align="center" align="center" />
        <el-table-column v-if="th[0].check" prop="name" label="客户名称" min-width="100" header-align="center" align="center">
          <template slot-scope="scope">
            <div>{{ scope.row.name }}</div>
            <span class="remarks">{{ scope.row.remarks }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="th[1].check" prop="progress" label="跟进状态" min-width="100" header-align="center" align="center" />
        <el-table-column v-if="th[2].check" prop="company" label="公司" min-width="250" header-align="center" align="center" >
          <template slot-scope="scope">
            {{ scope.row.company?scope.row.company:'--' }}
          </template>
        </el-table-column>
        <el-table-column v-if="th[3].check" prop="admin_name" label="被指派人" min-width="110" header-align="center" align="center" />
        <el-table-column v-if="th[4].check" prop="addperson" label="上传者" min-width="90" header-align="center" align="center" />
        <el-table-column v-if="th[5].check" prop="source" label="来源" min-width="130" header-align="center" align="center" />
        <!--<el-table-column v-if="th[6].check" prop="project" label="项目" min-width="130" header-align="center" align="center" >
          <template slot-scope="scope">
            {{ scope.row.project?scope.row.project:'&#45;&#45;' }}
          </template>
        </el-table-column>-->
        <el-table-column v-if="th[7].check" prop="created_at" label="注册时间" min-width="120" header-align="center" align="center" sortable >
          <template slot-scope="scope">
            {{ scope.row.created_at?parseTime(scope.row.created_at, '{y}-{m}-{d}'):'--' }}
          </template>
        </el-table-column>
        <el-table-column v-if="th[8].check" prop="updated_at" label="更新时间" min-width="160" header-align="center" align="center" sortable >
          <template slot-scope="scope">
            {{ scope.row['updated_at']?scope.row.updated_at:'--' }}
          </template>
        </el-table-column>
        <el-table-column v-if="th[9].check" prop="contact_next_time" label="联系时间" min-width="120" header-align="center" align="center" sortable fixed="right">
          <template slot-scope="scope">
            <el-tag :type="scope.row.contact_next_times.indexOf('逾期')>=0?'danger':scope.row.contact_next_times.indexOf('年')>=0?'info':scope.row.contact_next_times.indexOf('月')>=0?'warning':scope.row.contact_next_times.indexOf('已成交')>=0?'success':''">{{ scope.row.contact_next_times }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="200" header-align="center" align="center" fixed="right">
          <template slot-scope="scope">
            <el-tooltip content="沟通" placement="top">
              <el-button v-if="queryMatch(81)" type="success" size="small" icon="el-icon-service" class="bg-green" circle @click="toRecord(scope.row)" />
            </el-tooltip>
            <el-tooltip content="详情" placement="top">
              <el-button type="primary" size="small" icon="el-icon-search" circle @click="toModify('客户详情', scope.row)" />
            </el-tooltip>
            <el-tooltip content="激活" placement="top">
              <el-button v-if="scope.row.cust_state===0&&queryMatch(81)" type="warning" size="small" icon="el-icon-check" circle @click="toModify('客户激活', scope.row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-if="queryMatch(82)" type="danger" size="small" icon="el-icon-close" circle @click="toDelete(scope.row)"/>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page.sync="currentPage"
        :page-size="pageSize"
        :page-sizes="pageSizes"
        :total="total"
        class="pagination"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"/>
    </el-card>

    <el-dialog :visible.sync="dialogVisible" title="客户指派" width="500px" class="dialog" center>
      <div class="content">
        <div class="text">将所选 {{ multipleSelection.length }} 位客户指派至
          <el-radio-group v-model="transfer.where">
            <!--<el-radio :label="0">公海</el-radio>-->
            <el-radio :label="1">销售</el-radio>
          </el-radio-group>
        </div>
        <el-select v-if="transfer.where==1" v-model="transfer.toId" placeholder="请选择指派用户" filterable>
          <el-option v-for="item in recommendList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="doTransfer">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ColumnController } from '../../components'
import { handleSortChange, handleSizeChange, handleCurrentChange, columnCheck, parseTime, dateJudge } from '@/utils/table'

export default {
  components: { ColumnController },
  data() {
    return {
      isShow: false,
      // ImageUrl: this.$store.getters.serverUrl,
ImageUrl: '',
      modelUrl: this.$store.getters.serverUrl + '/admin/customer/export?action=demo&token=' + this.$store.getters.token,
      searchTerms: {
        source: '',
        cust_state: '',
        recommend: '',
        progress: '丢单',
        date1: [],
        date2: [],
        searchValue: '',
        contact_status: ''
      },
      downloadLoading: false,

      sourceList: [], // 来源列表
      recommendList: [], // 指派人列表
      allMemberList: [], // 所有人员列表

      dialogVisible: false,
      transfer: {
        id: '',
        where: 0,
        toId: ''
      },

      // 表格相关数据
      tableMaxHeight: document.documentElement.clientHeight - 320,
      multipleSelection: [],
      tableLoading: false,
      currentPage: 1,
      pageSize: this.$store.getters.userInfo.pageSize,
      pageSizes: [10, 20, 50, 100, 1000],
      total: 0,
      tableData: [],
      th: [{ name: '客户名称', check: true },
        { name: '跟进状态', check: true },
        { name: '公司', check: true },
        { name: '指派人', check: true },
        { name: '上传者', check: true },
        { name: '来源', check: true },
        { name: '项目', check: true },
        { name: '注册时间', check: true },
        { name: '更新时间', check: true },
        { name: '联系时间', check: true }]
    }
  },
  watch: {
    $route(to) {
      if (to.name === '丢单客户') {
        this.getData()
        setTimeout(() => {
          this.isShow = true
        }, 300)
      } else {
        this.isShow = false
      }
    }
  },
  created() {
    if (this.$route.name === '丢单客户') {
      this.isShow = true
      this.getData()
      this.getSourceList()
      this.getRecommendList()
      this.getAllMemberList()
    }
  },
  methods: {
    handleCurrentChange, handleSizeChange, handleSortChange, columnCheck, parseTime, dateJudge,
    /**
     * 对应接口用户列表("customer/list"),
     * token  用户凭证  (必填)
     * page_no   当前页码
     * page_size   每页数量
     * sortName  排序字段名
     * sortOrder   排序方式
     * search  关键词
     * start_time  注册开始时间
     * end_time  注册结束时间
     * min_balance  最小余额
     * max_balance  最大余额
     * level  客户等级
     * status  客户状态
     * return: {
     *     "id":162,
     *     "name":"111",
     *     "realname":"李古奇",
     *     "type":1,
     *     "mobile":"16655160908",
     *     "recommend":23,
     *     "addperson":"彭梓龙",
     *     "email":"Myp1397217046@163.com",
     *     "position":"0",
     *     "company":"0",
     *     "wechat":"paris1069g",
     *     ""qq":"",
     *     ""contact_next_time":null,
     *     ""source":"腾讯云体验",
     *     ""project":"null",
     *     ""progress":"成单签约",
     *     ""status":0,
     *     ""remarks":"李总已购买分销1680",
     *     ""cust_state":0,
     *     ""created_at":"0000-00-00 00:00:00",
     *     ""updated_at":null,
     *     ""admin_name":"彭梓龙"
     * }
     * */
    getData(order) {
      this.tableLoading = true
      order || (order = {})
      const url = 'customer/list'
      const data = {
        page_no: this.currentPage,
        page_size: this.pageSize,
        search: this.searchTerms.searchValue,
        source: this.searchTerms.source,
        cust_state: this.searchTerms.cust_state,
        recommend: this.searchTerms.recommend,
        progress: this.searchTerms.progress,
        contact_status: this.searchTerms.contact_status
      }
      this.searchTerms.date1 && this.searchTerms.date1.length !== 0 && (data.start_time = this.searchTerms.date1[0] + ' 00:00:00', data.end_time = this.searchTerms.date1[1] + ' 23:59:59')
      this.searchTerms.date2 && this.searchTerms.date2.length !== 0 && (data.next_start_time = this.searchTerms.date2[0] + ' 00:00:00', data.next_end_time = this.searchTerms.date2[1] + ' 23:59:59')
      order.sortName && (data.sortName = order.sortName)
      order.sortOrder && (data.sortOrder = order.sortOrder)
      this.$store.dispatch('GetConnect', { url, data }).then(res => {
        this.tableData = res.data.rows
        if ((typeof this.tableData) === 'object') {
          const arr = []
          for (const key in this.tableData) {
            if (this.tableData.hasOwnProperty(key)) {
              arr.push(this.tableData[key])
            }
          }
          this.tableData = arr
        }
        this.total = res.data.total
        this.tableLoading = false
        this.uploadLoading = false
      }).catch(e => {
        this.tableLoading = false
        this.uploadLoading = false
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    /**
     *  获取来源列表
     *  接口:'member/source-list'
     */
    getSourceList() {
      const url = 'member/source-list'
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.sourceList = res.data
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    /**
     *  获取离职用户列表
     *  接口:'user/admin-list'
     */
    getAllMemberList() {
      const url = 'user/admin-list'
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.allMemberList = res.data.list
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    /**
     *  获取系统用户列表
     *  接口:'user/all-list'
     */
    getRecommendList() {
      const url = 'user/all-list'// 不包含离职人员
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.recommendList = res.data
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    toTransfer(where) {
      this.dialogVisible = true
      this.transfer.where = where
    },
    doTransfer() {
      if (this.multipleSelection.length === 0) {
        this.$message.error('请选择要转移的客户')
        this.dialogVisible = false
      } else if (this.transfer.toId === '') {
        this.$message.error('请选择要将客户指派给哪个销售')
      } else {
        const url = 'customer/ajax/' + this.transfer.toId
        const data = {
          action: 'batch_assign',
          id: this.transfer.toId,
          list: []
        }
        this.multipleSelection.forEach(item => {
          data.list.push(item.id)
        })
        data.list = data.list.join(',')
        this.$store.dispatch('GetConnect', { url, data }).then(res => {
          this.$message.success(res.msg)
          this.dialogVisible = false
          this.getData()
        }).catch((err) => {
          this.$message.error(err.msg)
        })
      }
    },
    toDelete(row) {
      this.$confirm('此操作将删除该客户线索, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const url = 'customer/delete/' + row.id
        this.$store.dispatch('GetConnect', { url }).then(res => {
          this.$message.success(res.msg)
          this.getData()
        }).catch((err) => {
          this.$message.error(err.msg)
        })
      })
    },
    toDeleteMore() {
      if (this.multipleSelection.length === 0) {
        this.$message.error('请选择要删除的客户')
        this.dialogVisible = false
      } else {
        this.$confirm('此操作将删除所选客户线索, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const url = 'customer/deleteall'
          const data = {
            id: []
          }
          this.multipleSelection.forEach(item => {
            data.id.push(item.id)
          })
          data.id = data.id.join(',')
          this.$store.dispatch('GetConnect', { url, data }).then(res => {
            this.$message.success(res.msg)
            this.getData()
          }).catch((err) => {
            this.$message.error(err.msg)
          })
        })
      }
    },
    toRecord(row) {
      this.isShow = false
      this.$router.push({
        path: '/customer/mine/record',
        query: { id: row.id }
      })
    },
    toModify(title, row) {
      this.isShow = false
      const query = { title: title }
      row && (query.id = row.id)
      this.$router.push({
        path: '/customer/mine/modify',
        query: query
      })
    },

    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 导出
    handleDownload() {
      if (this.multipleSelection.length === 0) {
        this.$message.error('请选择要导出的客户')
      } else {
        this.downloadLoading = true
        // import('@/vendor/Export2Excel').then(excel => {
        //   const tHeader = ['客户名称', '跟进状态', '公司', '指派人', '上传者', '来源', '项目', '注册时间', '更新时间', '联系时间']
        //   const filterVal = ['customer_name', 'customer_status', 'company', 'assignor', 'uploader', 'source', 'project', 'signin_date', 'updata_date', 'contact_date']
        //   const list = this.tableData
        //   const data = this.formatJson(filterVal, list)
        //   excel.export_json_to_excel({
        //     header: tHeader,
        //     data,
        //     filename: '客户列表',
        //     autoWidth: true
        //   })
        //   this.downloadLoading = false
        // })
        let list = []
        this.multipleSelection.forEach(item => {
          list.push(item.id)
        })
        list = list.join(',')
        window.open(`${this.$store.getters.serverUrl}/admin/customer/export?action=data&token=${this.$store.getters.token}&list=${list}&mallId=${this.$store.getters.SaaSId}`)
        this.downloadLoading = false
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>

<style lang="scss" type="text/scss" scoped>
@import '../../../styles/index.scss';
.box-1 {
  .header {
    .bar {
      line-height: 50px;
    }
    > div {
      @include flex-row(center, flex-start);
      padding: 2px 0;
      flex-wrap: wrap;
      .upload {
        padding: 0 10px;
      }
      .select {
        padding-right: 15px;
        width: 160px;
      }
      .picker {
        margin-right: 15px;
        width: 300px;
      }
      .do-btn {
        @extend .bg-green;
        margin-left: 6px;
      }
      .search-input {
        width: 240px;
      }
    }
  }
}
.dialog {
  .content {
    text-align: center;
    .text {
      padding-bottom: 20px;
      .el-radio-group {
        padding-left: 15px;
      }
    }
  }
}
  .remarks{
    font-size: 12px;
    color: $textGray;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    line-height: 0px;
  }

</style>
